﻿using CarAppClient.Consts;
using CarAppClient.Controls.MessageUsercontrols;
using CarAppClient.Extension;
using CarAppClient.Helpers;
using CarAppClient.ViewModels;
using CarAppClient.Views.CarType.Views;
using CarAppDto.CarType.CountryDtos;
using CarAppDto.CarType.CarDtos;
using D.UtilCore.Dtos;
using System.Collections.ObjectModel;
using System.Xml.Linq;
using Autofac.Features.OwnedInstances;
using Newtonsoft.Json;
using CarAppClient.Views.Rule.Views;
using CarAppDto.Rule.RuleMappingDtos;
using CarAppDto.Rule.RuleConfigDtos;
using System.Windows.Controls;
using D.UtilSqlsugarOrm;
using D.WPF.MVVM.EventUtil;
using DelegateCommand = D.WPF.MVVM.EventUtil.DelegateCommand;
using System.Windows;
using CarAppDto.Common;

namespace CarAppClient.Views.Rule.ViewModels.RuleMapping
{
    public class RuleMappingQueryViewModel : BaseQueryViewModel<Page_RuleMapping_Query, RepRuleMapping>
    {
        #region 加载页面数据     
        RepRuleMapping _repRuleMapping;

        Page_RuleMapping_Query _owner;
        string _ruleId;
        public RuleMappingQueryViewModel(Page_RuleMapping_Query owner, string? type,string ruleId) : base(owner, type)
        {
            _owner = owner;
            _ruleId = ruleId;
            Query();
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="repCarType"></param>
        protected async override void LoadData()
        {
            Data = new ObservableCollection<RepRuleMapping>();
        }

        #region 查询条件

        private string? name;
        /// <summary>
        /// 名称
        /// </summary>
        public string? Name
        {
            get { return name; }
            set { name = value; RaisePropertyChanged(); }
        }

        #endregion
        #region 查询


        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="repCarType"></param>
        protected override async void Query(object? obj = null)
        {
            if (Data != null)
            {
                Data.Clear();
            }
            else
            {
                Data = new ObservableCollection<RepRuleMapping>();
            }

            // 请求后端接口 
            var res = await HttpHelper<PageModel<RepRuleMapping>>.PostAsync(ApiUrl.QueryRuleMappingPages, new ReqQueryRuleMappingPage()
            {
                RuleId = _ruleId,
                PageSize = PageSize,
                PageNo = PageNo
            });

            //  判断结果
            if (res.Code == StatusCodeEnum.Waring)
            {
                MsgUtil.Warning(res.ErrorMsg);
            }
            else if (res.Code == StatusCodeEnum.Error)
            {
                MsgUtil.Error(res.ErrorMsg);
            }
            else if (res.Code == StatusCodeEnum.ServerError)
            {
                MsgUtil.Error("服务器异常");
            }
            else if (res.Code == StatusCodeEnum.OK)
            {
                // 绑定数据源到UI 
                if (res.Data != null)
                {
                    foreach (var item in res.Data.Data)
                    {
                        item.IsSelected = false;
                        Data.Add(item);
                    }

                    TotalCount = res.Data.TotalCount;
                    TotalPage = res.Data.TotalPage;

                    base.RefPage();
                }
            }
            else
            {
                MsgUtil.Error(res.Code.ToString());
            }
        }
        #endregion
        #endregion

        // 事件
        public event InformationRequestedHandler InformationRequested;
        protected override async void Submit(object? obj = null)
        {
            if (obj == null) return;
            List<RepRuleMapping> listRuleMapping =JsonConvert.DeserializeObject<List<RepRuleMapping>>( JsonConvert.SerializeObject(obj));
            if(listRuleMapping.FindAll(a=>a.IsSelected==true).Count()>1)
            {
                MsgUtil.Error("只能选择一个");
                return;
            }
            if (listRuleMapping.FindAll(a => a.IsSelected == true).Count()==0)
            {
                MsgUtil.Error("请选择一个");
                return;
            }
            _repRuleMapping = listRuleMapping.FirstOrDefault(a=>a.IsSelected==true);       
            _owner.Close();
            InformationRequested?.Invoke(this, new InformationEventArgs<RepRuleMapping>(_repRuleMapping));
        }

        #region 新增
        /// <summary>
        /// 新增事件
        /// </summary>
        private DelegateCommand? _addCommand;
        /// <summary>
        /// 新增事件
        /// </summary>
        public DelegateCommand AddCommand => _addCommand ?? (_addCommand = new DelegateCommand(Add));
        /// <summary>
        /// 新增
        /// </summary>
        protected  void Add(object? obj) {
            Page_RuleMapping_Modify view = new Page_RuleMapping_Modify(ruleId:_ruleId,viewStatus:ViewStatus.Add);
            view.ShowDialog();

            // 刷新数据
            LoadData();
            Query();
        }
        #endregion

   
        #region 批量删除
        /// <summary>
        /// 批量删除事件
        /// </summary>
        private DelegateCommand? _batchDeleteCommand;
        /// <summary>
        /// 批量删除事件
        /// </summary>
        public DelegateCommand BatchDeleteCommand => _batchDeleteCommand ?? (_batchDeleteCommand = new DelegateCommand(BatchDelete));
        protected async void BatchDelete(object? obj) {
            // 基础数据判断
            if (Data == null)
            {
                MsgUtil.Warning("暂无数据可删除");
                // 刷新数据
                LoadData();
                return;
            }

            if (!Data.Any(m => m.IsSelected))
            {
                MsgUtil.Warning("请选择要删除的数据"); return;
            }

            // 二次询问提示
            var messageBoxResult = MsgUtil.Question("确定删除吗？");
            if (messageBoxResult == MessageBoxResult.OK)
            {
                // 获取要删除的数据 
                var ids = Data.Where(m => m.IsSelected).Select(m => m.Id).ToList();

                // 请求后端接口 
                var res = await HttpHelper<int>.DeleteAsync($"{ApiUrl.DeleteRuleMapping}/{string.Join(",", ids)}");
                if (res.IsSuccess)
                {
                    //  判断结果
                    MsgUtil.ShowMsg(res.Code, res.ErrorMsg, "删除成功");

                    // 刷新数据
                    LoadData();
                    Query();
                }
                else
                {
                    MsgUtil.ShowMsg(res.Code, res.ErrorMsg, "删除失败");
                }
            }
        }

        #endregion

        #region 修改  
        private DelegateCommandT<RepRuleMapping>? _updateCommand;
        public DelegateCommandT<RepRuleMapping> UpdateCommand => _updateCommand ?? (_updateCommand = new DelegateCommandT<RepRuleMapping>(Update));

        protected  void Update(RepRuleMapping? vm)
        {
            if (vm != null)
            {
                Page_RuleMapping_Modify view = new Page_RuleMapping_Modify(id:vm.Id,ruleId: _ruleId,viewStatus:ViewStatus.Update);
                view.ShowDialog();

                // 刷新数据
                LoadData();
                Query();
            }
        }
        #endregion
    }

}
